package cn.fay.chapter18;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipCompress {

	public static void main(String[] args) throws IOException{
		FileOutputStream f = new FileOutputStream("test.zip");
		CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
		ZipOutputStream zos = new ZipOutputStream(csum);
		BufferedOutputStream out = new BufferedOutputStream(zos);
		
		zos.setComment("A test of Java Zipping");
		
		BufferedInputStream in=new BufferedInputStream(new FileInputStream("file.txt"));
		zos.putNextEntry(new ZipEntry("file.txt"));
		int c;
		while((c=in.read())!=-1)
			out.write(c);
		in.close();
		out.flush();
		
		in=new BufferedInputStream(new FileInputStream("out.txt"));
		zos.putNextEntry(new ZipEntry("out.txt"));
		c=-1;
		while((c=in.read())!=-1)
			out.write(c);
		in.close();
		out.flush();
		out.close();
		
		System.out.println("Checksum: "+csum.getChecksum().getValue());
		System.out.println("Reading File");
		FileInputStream fi=new FileInputStream("test.zip");
		CheckedInputStream csumi=new CheckedInputStream(fi, new Adler32());
		ZipInputStream in2=new ZipInputStream(csumi);
		BufferedInputStream bis=new BufferedInputStream(in2);
		ZipEntry ze;
		while((ze=in2.getNextEntry())!=null){
			System.out.println("Reading file "+ze);
			ByteArrayOutputStream baos=new ByteArrayOutputStream();
			int x;
			while((x=bis.read())!=-1){
				baos.write(x);
			}
			System.out.println(new String(baos.toByteArray(),"gb2312"));
			System.out.println();
		}
		System.out.println("Checksum: "+csumi.getChecksum().getValue());
		bis.close();
		ZipFile zipFile=new ZipFile("test.zip");
		Enumeration<? extends ZipEntry> e = zipFile.entries();
		while (e.hasMoreElements()) {
			ZipEntry ze2=e.nextElement();
			System.out.println("File: "+ze2);
			bis = new BufferedInputStream(zipFile.getInputStream(ze2));
			ByteArrayOutputStream baos=new ByteArrayOutputStream();
			c=-1;
			while((c=bis.read())!=-1)
				baos.write(c);
			System.out.println(new String(baos.toByteArray(),"gb2312"));
		}
	}

}
